﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lm.Common.ExtensionMethods;
using Lm.Common.Auth.Operation;

namespace Lm.Common.Auth.Role
{
    /// <summary>
    /// 角色草稿编辑，只能修改操作状态下的角色
    /// </summary>
    [Operation.Operation("{6891788D-6ADB-4924-B208-0B8D9F6817C5}", "角色草稿编辑", "")]
    public class RoleDraftEditor : Operation.OperationBase
    {
        static RoleDraftEditor()
        {
            OperationBase.CreateOperation(typeof(RoleDraftEditor));
        }

        public RoleDraftEditor(string token)
            : base(token)
        { }

        public Model.Role Add(Model.Role role)
        {
            role.TrimStringProperty();
            role.RoleId = Guid.NewGuid();
            if (role.RoleCode.IsNullOrBlank())
            { throw new Exception("角色编号必填"); }
            if (role.RoleName.IsNullOrBlank())
            { throw new Exception("角色名必填"); }
            role.SetRoleStatus(Model.RoleStatus.Draft);
            using (var tran = new System.Transactions.TransactionScope())
            {
                var dal = Lm.Common.Auth.DAL.DALFactory.Create();
                if (dal.Exist<Model.Role>(t => t.RoleCode == role.RoleCode))
                { throw new Exception("角色编号" + role.RoleCode + "已存在"); }
                role.SetRoleStatus(Model.RoleStatus.Draft);
                if (dal.Insert<Model.Role>(role) == false)
                { throw new Exception("保存角色失败"); }
                tran.Complete();
                return role;
            }
        }

        public void RemoveRole(string roleCode)
        {
            using (var tran = new System.Transactions.TransactionScope())
            {
                var role = new RoleDal().GetByRoleCode(roleCode);
                if (role.GetRoleStatus() != Model.RoleStatus.Draft)
                { throw new Exception("只能删除草稿状态下的角色"); }
                var helper = Lm.Common.Auth.DAL.DALFactory.Create();

                helper.Delete<Model.RolePermission>(t => t.RoleId == role.RoleId);
                helper.Delete<Model.Role>(t => t.RoleId == role.RoleId);

                tran.Complete();
            }
        }

        public void EditRole(Model.Role role)
        {
            role.TrimStringProperty();
            if (role.RoleCode.IsNullOrBlank())
            { throw new Exception("角色编号必填"); }
            if (role.RoleName.IsNullOrBlank())
            { throw new Exception("角色名必填"); }
            
            using (var tran = new System.Transactions.TransactionScope())
            {
                var data = new RoleDal().GetByRoleCode(role.RoleCode);
                if (data.GetRoleStatus() != Model.RoleStatus.Draft)
                { throw new Exception("角色不是草稿状态，不能修改"); }
                data.Pause = role.Pause;
                data.RoleName = role.RoleName;
                data.RoleRemark = role.RoleRemark;
                if (DAL.DALFactory.Create().Update<Model.Role>(data, t => t.RoleId == data.RoleId) != 1)
                { throw new Exception("修改角色失败"); }
                tran.Complete();
            }
        }

        /// <summary>
        /// 给角色授权
        /// </summary>
        /// <param name="roleCode"></param>
        /// <param name="operationIdList"></param>
        public void Authorize(string roleCode, params Guid[] operationIdList)
        {
            if (roleCode.IsNullOrBlank())
            { throw new Exception("角色编号不能为空"); }
            if (operationIdList.Length == 0)
            { throw new Exception("权限列表不能为空"); }
            using (var tran = new System.Transactions.TransactionScope())
            {
                var role = new RoleDal().GetByRoleCode(roleCode);
                if (role.GetRoleStatus() != Model.RoleStatus.Draft)
                { throw new Exception("角色不是草稿状态，不能授权"); }
                var helper = DAL.DALFactory.Create();
                helper.Delete<Model.RolePermission>(t => t.RoleId == role.RoleId);
                foreach (var operationId in operationIdList)
                {
                    var operation = new OperationDal().GetById(operationId);
                    if (helper.Insert<Model.RolePermission>(new Model.RolePermission()
                      {
                          Id = Guid.NewGuid(),
                          RoleId = role.RoleId,
                          OperationId = operationId
                      }) == false)
                    { throw new Exception("授权失败"); }
                }
                tran.Complete();
            }
        }
    }
}
